package cn.chengpengper.domain.strategy.service.armory.impl;

import cn.chengpengper.domain.strategy.model.StrategyAwardEntity;
import cn.chengpengper.domain.strategy.model.StrategyEntity;
import cn.chengpengper.domain.strategy.model.StrategyRuleEntity;
import cn.chengpengper.domain.strategy.repository.IStrategyRepository;
import cn.chengpengper.domain.strategy.service.armory.IStrategyArmory;
import cn.chengpengper.domain.strategy.service.armory.IStrategyDispatch;
import cn.chengpengper.types.common.Constants;
import cn.chengpengper.types.enums.ResponseCode;
import cn.chengpengper.types.exception.AppException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.security.SecureRandom;
import java.util.*;

/*@formatter:off*/

/**
 * ____________________
 * < 神兽护体，永无bug! >
 * --------------------
 *
 * @author huchengpeng
 * @version v1.0.0
 * @date 2024/7/27 13:39
 * @description 抽奖策略调度实现
 */

/*@formatter:on*/

@Slf4j
@Service
public class StrategyArmoryDispatchImpl implements IStrategyArmory, IStrategyDispatch {

    @Resource
    private IStrategyRepository strategyRepository;

    @Override
    public boolean assembleStrategy(Long strategyId) {
        // 根据策略id查询对应奖品列表
        List<StrategyAwardEntity> strategyAwardEntities = strategyRepository.queryStrategyAwardList(strategyId);
        assembleStrategy(String.valueOf(strategyId), strategyAwardEntities);

        // 根据策略id查询抽奖策略
        StrategyEntity strategyEntity = strategyRepository.queryStrategyEntityByStrategyId(strategyId);
        // 权重策略配置 - 适用于 rule_weight 权重规则配置
        String ruleWeight = strategyEntity.getRuleWeight();
        if(Objects.isNull(ruleWeight)){
            return true;
        }

        StrategyRuleEntity strategyRuleEntity = strategyRepository.queryStrategyRule(strategyId, ruleWeight);
        if(Objects.isNull(strategyRuleEntity)){
            throw new AppException(ResponseCode.STRATEGY_RULE_WEIGHT_IS_NULL.getCode(),ResponseCode.STRATEGY_RULE_WEIGHT_IS_NULL.getInfo());
        }

        Map<String, List<Integer>> ruleWeightValueMap = strategyRuleEntity.getRuleWeightValues();
        /**
         * ruleWeightValueMap:
         * 6000:[102,103,104,105,106,107,108,109]
         */
        Set<String> keys = ruleWeightValueMap.keySet();
        for (String key : keys) {
            List<Integer> ruleWeightValues = ruleWeightValueMap.get(key);
            ArrayList<StrategyAwardEntity> strategyAwardEntitiesClone = new ArrayList<>(strategyAwardEntities);
            // 排除掉不属于此规则的奖品
            strategyAwardEntitiesClone.removeIf(entity-> !ruleWeightValues.contains(entity.getAwardId()));
            assembleStrategy(String.valueOf(strategyId).concat(Constants.UNDER_LINE).concat(key),strategyAwardEntitiesClone);
        }
        return true;
    }

    private void assembleStrategy(String key, List<StrategyAwardEntity> strategyAwardEntities) {
        // 2、获取概率最小值
        BigDecimal minAwardRate = strategyAwardEntities.stream()
                .map(StrategyAwardEntity::getAwardRate)
                .min(BigDecimal::compareTo)
                .orElse(BigDecimal.ZERO);

        // 3、获取概率总和
        BigDecimal totalAwardRate = strategyAwardEntities.stream()
                .map(StrategyAwardEntity::getAwardRate)
                .reduce(BigDecimal.ZERO, BigDecimal::add);

        // 4、用1%0.1获得概率范围
        BigDecimal rateRange = totalAwardRate.divide(minAwardRate, 0, RoundingMode.CEILING);

        //5、生成策略奖品概率查找表，占位越多等于概率高
        List<Integer> strategyAwardSearchRateTables = new ArrayList<>(rateRange.intValue());
        for (StrategyAwardEntity strategyAward : strategyAwardEntities) {
            Integer awardId = strategyAward.getAwardId();
            BigDecimal awardRate = strategyAward.getAwardRate();
            // 计算出每个概率值需要存放到查找表的数量，循环填充
            for (int i = 0; i < rateRange.multiply(awardRate).setScale(0, RoundingMode.CEILING).intValue(); i++) {
                strategyAwardSearchRateTables.add(awardId);
            }
        }

        // 6、对存储的奖品进行乱序操作
        Collections.shuffle(strategyAwardSearchRateTables);

        //7、生成出Map集合，key对应的就是概率值，通过概率来获得对应的奖品id
        Map<Integer, Integer> shuffleStrategyAwardSearchRateTable = new LinkedHashMap<>();
        for (int i = 0; i < strategyAwardSearchRateTables.size(); i++) {
            shuffleStrategyAwardSearchRateTable.put(i, strategyAwardSearchRateTables.get(i));
        }

        // 8、存放到 Redis
        strategyRepository.storeStrategyAwardSearchRateTable(key, shuffleStrategyAwardSearchRateTable.size(), shuffleStrategyAwardSearchRateTable);
    }

    @Override
    public Integer getRandomAwardId(Long strategyId) {
        // 获取抽奖策略范围
        int rateRange = strategyRepository.getRateRange(strategyId);
        // 通过生成的随机值，根据概率查找表获取结果
        return strategyRepository.getStrategyAwardAssemble(String.valueOf(strategyId),new SecureRandom().nextInt(rateRange));
    }

    @Override
    public Integer getRandomAwardId(Long strategyId, String ruleWeightValue) {
        String cacheKey = String.valueOf(strategyId).concat(Constants.UNDER_LINE).concat(ruleWeightValue);
        int rateRange = strategyRepository.getRateRange(cacheKey);
        return strategyRepository.getStrategyAwardAssemble(cacheKey,new SecureRandom().nextInt(rateRange));
    }
}
